﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Fcom.VNInsurance.Web.CultureHelper;
using System.Text;
using System.IO;
using System.Net;
//using Facebook;
//using Newtonsoft.Json;
//using Newtonsoft.Json.Linq;
//using System.Web.Security;
namespace Fcom.VNInsurance.Web.Controllers
{
    public class HomeController : CultureController
    {
        //
        // GET: /Home/
        //private Facebook.FacebookClient fbclient;
        private string access_token;
   
        Fcom.VNInsurance.Web.Models.VNInsuranceDataContext db = new Models.VNInsuranceDataContext();
        public ActionResult Index()
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 1);

            return View(news);
        }

        public ActionResult facebookconnect()
        {/*
            Models.FBUserInfo fbuser =null;
            string app_id = "564998036927139";
            string app_secret = "a3a61d632720bd45b13732077e8deda7";
            string scope = "publish_stream,manage_pages";

            if (Request["code"] == null)
            {
                Response.Redirect(string.Format(
                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, Request.Url.AbsoluteUri, scope));
                Session["fb_accesstoken"] = null;
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                    app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string vals = reader.ReadToEnd();

                    foreach (string token in vals.Split('&'))
                    {
                        //meh.aspx?token1=steve&token2=jake&...
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }

                access_token = tokens["access_token"];
                Session["fb_accesstoken"] = access_token;
                fbclient = new FacebookClient(access_token);
                var jsonfb = fbclient.Get("me", new { fields = "id,name,first_name,last_name,link,username,gender,locale,email,picture,birthday" });
                fbuser = JsonConvert.DeserializeObject<Models.FBUserInfo>(jsonfb.ToString());
                Fcom.IDLib.SaveMoneyID.AccountsynClient acsyn = new IDLib.SaveMoneyID.AccountsynClient();
                if (acsyn.checkemailexists(fbuser.username))
                {
                    FormsAuthentication.SetAuthCookie(fbuser.email, true);
                    return RedirectToAction("Index");
                }
                else
                {
                    acsyn.CreateAccountFl(fbuser.email, "", fbuser.name, (fbuser.gender == "male" ? true : false), 1, fbuser.birthday);
                    FormsAuthentication.SetAuthCookie(fbuser.email, true);
                    return RedirectToAction("Index");
                }
            }
          * */
            return View();
        }
      
        public ActionResult SiteMap()
        {
            Response.ContentType = "text/xml";
            var products = db.Products;
            return View(products);
        }
        public ActionResult BottomSXml(string ID)
        {
            Response.ContentType = "text/xml";
            var sxml = db.MenuLangs.Where(m => m.LangID == ID && m.Menu.MenuPosID == 1);
            return View(sxml);
        }
        public ActionResult About()
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 4);

            return View(news);
        }
        public ActionResult Term()
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 5);

            return View(news);
        }
       
        public ActionResult Complaint()
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 6);

            return View(news);
        }
        public ActionResult Career()
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 2).OrderByDescending(m=>m.NewsID);

            return View(news);
        }
        public ActionResult Contact(string msg)
        {
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 3);
            ViewBag.Supporteam = new SelectList(db.SupportTeamLangs.Where(t => t.LangID == Request.Cookies["_culture"]["lang"]), "SupportTeamID", "DisplayName");
            ViewBag.msg = msg;
            return View(news);
        }
        public ActionResult TopMostView()
        {
            var topmost = db.TopMostProductLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]).OrderBy(m=>m.TopMostProduct.Position);
            return PartialView(topmost);
        }
        public string GetIpAddress()  // Get IP Address
        {
            string VisitorsIPAddr = string.Empty;
            if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                VisitorsIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (Request.UserHostAddress.Length != 0)
            {
                VisitorsIPAddr = Request.UserHostAddress;
            }
            return "Your IP is: " + VisitorsIPAddr;
        }

        public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }
        [Authorize(Roles="13,14")]
        public ActionResult Cpanel()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            Models.UserIpInfo us = new Models.UserIpInfo();
            us.computername = "is"+sIPAddress;
            us.ipaddress = GetIPAddress();
            return View(us);
        }
        [HttpPost]
        public ActionResult Contact(string CaptchaValue,Fcom.VNInsurance.Web.Models.SupportNew model)
        {
            if (ModelState.IsValid)
            {
                string captchaHash = Session["ContactCaptcha"].ToString();
                CaptchaValue = CaptchaValue.ToUpper();
                 //string cpv=Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(CaptchaValue)));
                if (captchaHash == CaptchaValue)
                {

                    Fcom.VNInsurance.Web.Models.SupportNew spnews = new Models.SupportNew();
                    spnews.Email = model.Email;
                    spnews.FullContent = model.FullContent;
                    spnews.RequireteamID = 1;
                    spnews.Title = model.Title;
                    var smtpconfig = db.ConfigSMTPs.FirstOrDefault();
                    var supportteam = db.SupportTeams.Where(t => t.ID == 1).FirstOrDefault();
                    var supportters = supportteam.Supporters;
                    db.SupportNews.InsertOnSubmit(spnews);
                    db.SubmitChanges();
                    foreach (var spter in supportters)
                    {
                        Fcom.VNInsurance.Web.Infrastructure.SMTPSendMail.SendOneEmail(smtpconfig, spter.Email, "[Liên hệ-" + supportteam.Name + "]" + model.Title, "Khách hàng(Email):" + model.Email + "<br> Gửi yêu cầu tới " + supportteam.Name + "<br><br>Tiêu đề:" + model.Title + "<br><br>Nội dung: " + model.FullContent + "<br><br><br>Để hỗ trợ vui lòng click vào link này: " + Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("Answer", "Support", new { SupportContentID = spnews.ID }), true);
                        
                    }
                    return RedirectToAction("Contact", new { msg = "SendSuccess" });
                }
                else
                {
                    ModelState.AddModelError("CaptchInvalid", "Captcha invalid");
                }
                
            }
            var news = db.NewsLangs.Where(n => n.LangID == Request.Cookies["_culture"]["lang"] && n.New.NCatID == 3);
            ViewBag.Supporteam = new SelectList(db.SupportTeamLangs.Where(t => t.LangID == Request.Cookies["_culture"]["lang"]), "SupportTeamID", "DisplayName");
            return View(news);
        }
        public ActionResult GetContactCaptcha()
        {
            //Captcha Image Size  Width - Height
            int width = 125;
            int height = 25;

            //Captcha String
            dynamic fontFamily = "Tahoma";
            // -  Generate Random
            int randomsize = 5;
            StringBuilder randomstringbuilder = new StringBuilder();
            Random random = new Random(DateTime.Now.Millisecond);
            char ch = '\0';
            for (int i = 0; i <= randomsize - 1; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                randomstringbuilder.Append(ch);
            }
            dynamic captchaString = randomstringbuilder.ToString();

            // Create a new 32-bit bitmap image.
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Create a graphics object for drawing.
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);

            // Fill in the background.
            System.Drawing.Drawing2D.HatchBrush hatchBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.Wave, System.Drawing.Color.LightGray, System.Drawing.Color.White);
            g.FillRectangle(hatchBrush, rect);

            // Set up the text font.
            System.Drawing.SizeF size = default(System.Drawing.SizeF);
            float fontSize = rect.Height + 1;
            System.Drawing.Font font = null;
            System.Drawing.StringFormat format = new System.Drawing.StringFormat();
            format.Alignment = System.Drawing.StringAlignment.Center;
            format.LineAlignment = System.Drawing.StringAlignment.Center;

            // Adjust the font size until the text fits within the image.
            do
            {
                fontSize -= 1;
                font = new System.Drawing.Font(fontFamily, fontSize, System.Drawing.FontStyle.Bold);
                size = g.MeasureString(captchaString, font, new System.Drawing.SizeF(width, height), format);
            } while (size.Width > rect.Width);

            // Create a path using the text and warp it randomly.
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddString(captchaString, font.FontFamily, Convert.ToInt32(font.Style), font.Size, rect, format);
            float v = 4f;
            System.Drawing.PointF[] points = {
		new System.Drawing.PointF(random.Next(rect.Width) / v, random.Next(rect.Height) / v),
		new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v, random.Next(rect.Height) / v),
		new System.Drawing.PointF(random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v),
		new System.Drawing.PointF(rect.Width - random.Next(rect.Width) / v, rect.Height - random.Next(rect.Height) / v)
	};
            System.Drawing.Drawing2D.Matrix matrix = new System.Drawing.Drawing2D.Matrix();
            matrix.Translate(0f, 0f);
            path.Warp(points, rect, matrix, System.Drawing.Drawing2D.WarpMode.Perspective, 0f);

            // Draw the text.
            hatchBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.DashedUpwardDiagonal, System.Drawing.Color.DarkGray, System.Drawing.Color.Black);
            g.FillPath(hatchBrush, path);

            // Add some random noise.
            int m = Math.Max(rect.Width, rect.Height);
            for (int i = 0; i <= Convert.ToInt32(Math.Truncate(rect.Width * rect.Height / 30f)) - 1; i++)
            {
                int x = random.Next(rect.Width);
                int y = random.Next(rect.Height);
                int w = random.Next(m / 50);
                int h = random.Next(m / 50);
                g.FillEllipse(hatchBrush, x, y, w, h);
            }

            // Clean up.
            font.Dispose();
            hatchBrush.Dispose();
            g.Dispose();

            FileContentResult captchaImageResult = null;
            using (System.IO.MemoryStream mystream = new System.IO.MemoryStream())
            {

                bitmap.Save(mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
                captchaImageResult = base.File(mystream.GetBuffer(), "image/jpeg");

            }
            bitmap.Dispose();

            //Save the Captcha Hash in the Session
            Session["ContactCaptcha"] = captchaString;

            //Return the Captcha Image
            return captchaImageResult;

        }
        public ActionResult CompanyPartners()
        {
            var company = db.CompanyLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]&&m.Company.Enable==true);
            return PartialView(company);
        }
        public ActionResult SaveUpToView()
        {
            var saveuptoview = db.SaveUpToLangs.Where(m => m.LangID == Request.Cookies["_culture"]["lang"]);
            return PartialView(saveuptoview);
        }
    }
}
